package com.xcd.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xcd.reggie.common.CustomException;
import com.xcd.reggie.dto.SetmealDto;
import com.xcd.reggie.entity.Setmeal;
import com.xcd.reggie.entity.SetmealDish;
import com.xcd.reggie.mapper.SetmealMapper;
import com.xcd.reggie.service.SetmealService;
import com.xcd.reggie.service.SetmelDishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper,Setmeal>  implements SetmealService {

    @Autowired
    private SetmelDishService setmelDishService;


    @Override
    @Transactional
    public void savWithDis(SetmealDto setmealDto) {
//        Setmeal setmeal = new Setmeal();
//        setmeal.setId(setmealDto.getId());
//        setmeal.setCode(setmealDto.getCode());
//        setmeal.setImage(setmealDto.getImage());
//        setmeal.setPrice(setmealDto.getPrice());
//        setmeal.setStatus(setmealDto.getStatus());
//        setmeal.setDescription(setmealDto.getDescription());
//        setmeal.setCategoryId(setmealDto.getCategoryId());
//        setmeal.setName(setmealDto.getName());
        this.save(setmealDto);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
            setmelDishService.save(setmealDish);
        }
    }

    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        //检查售卖状态，如果是售卖中则无法删除
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Setmeal::getId,ids);
        lambdaQueryWrapper.eq(Setmeal::getStatus,1);

        int count = this.count(lambdaQueryWrapper);
        if (count > 0){
            throw new CustomException("商品正在售卖中，无法删除");
        }

        //删除套餐
        this.removeByIds(ids);

        //删除套餐所关联的菜品

        LambdaQueryWrapper<SetmealDish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        setmelDishService.remove(dishLambdaQueryWrapper);


    }
}
